import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Tag, Typography, Modal } from 'antd';
import { EyeOutlined } from '@ant-design/icons';
import PortfolioDetail from './PortfolioDetail';

const { Title, Paragraph } = Typography;

const PortfolioList = () => {
  const [portfolios, setPortfolios] = useState([]);
  const [selectedPortfolio, setSelectedPortfolio] = useState(null);
  const [detailVisible, setDetailVisible] = useState(false);

  useEffect(() => {
    // 写入标准化的三组数据到localStorage（如已存在则不覆盖）
    if (!localStorage.getItem('portfolioListData')) {
      fetch('/portfolioListData.json')
        .then(res => res.json())
        .then(data => {
          localStorage.setItem('portfolioListData', JSON.stringify(data));
          setPortfolios(data);
        });
    } else {
      const stored = localStorage.getItem('portfolioListData');
      if (stored) {
        setPortfolios(JSON.parse(stored));
      }
    }
  }, []);

  const columns = [
    { title: '组合名称', dataIndex: ['portfolioInfo', 'name'], key: 'name' },
    { title: '风险等级', dataIndex: ['portfolioInfo', 'riskLevel'], key: 'riskLevel', render: v => <Tag color={v === '高风险' ? 'red' : v === '中风险' ? 'orange' : 'green'}>{v}</Tag> },
    { title: '创建方', dataIndex: ['portfolioInfo', 'creator'], key: 'creator' },
    { title: '上架日期', dataIndex: ['portfolioInfo', 'onShelfDate'], key: 'onShelfDate' },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button type="link" icon={<EyeOutlined />} onClick={() => { setSelectedPortfolio(record); setDetailVisible(true); }}>
          查看详情
        </Button>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Title level={3}>组合产品列表</Title>
      <Paragraph type="secondary">展示所有已创建的投资组合产品，点击可查看详细信息。</Paragraph>
      <Card>
        <Table dataSource={portfolios} columns={columns} rowKey={r => r.portfolioInfo.id} pagination={{ pageSize: 10 }} />
      </Card>
      <Modal
        open={detailVisible}
        onCancel={() => { setDetailVisible(false); setSelectedPortfolio(null); }}
        width="90vw"
        style={{ top: 20 }}
        footer={null}
        bodyStyle={{ padding: 0 }}
        destroyOnClose
      >
        {detailVisible && selectedPortfolio && <PortfolioDetail portfolio={selectedPortfolio} />}
      </Modal>
    </div>
  );
};

export default PortfolioList; 